<template>
  <div class="marker-container">
    <div class="detail-box" v-show="detailVisible">
      <i>{{detailTitle}}</i>
      <i class="close" @click="closeDetail">x</i>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import mapboxgl from "mapbox-gl";
import EventBus from "@/utils/eventBus";
import DeviceCard from "../components/deviceCard/index.vue";

mapboxgl.accessToken =
  "pk.eyJ1IjoidGhpYmF1dGciLCJhIjoiMzg5MzQzOGMwYTJmOGNlODRkYzJjMDc5ZDEwNjNkOTEifQ.YPJ4ALWlOKnLPeaS5Ose7g";

export default {
  components: {
  },
  data() {
    return {
      map: null, // 地图实例
      pointData: null, // 接口获取的marker点位数据
      defaultUserImg: null, // 默认marker点图片
      selectedUserImg: null, // 高亮marker点图片
      markerList: [], // 当前添加的marker集合
      deviceCardMarkerList: [], // 当前添加的设备卡片marker集合
      cardVisible: false,
      detailVisible: false,
      detailTitle: "",
    }
  },
  mounted() {
    EventBus.$on("clearSelMarker", () => {
      this.clearSelMarker()
    });
  },
  beforeDestroy() {
    EventBus.$off("clearSelMarker");
  },
  methods: {
    getPointData() {
      return new Promise((resolve, reject) => {
        const url = "https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson";
        fetch(url)
          .then(response => response.json())
          .then(data => {
            resolve(data);
          })
          .catch(error => {
            console.error("获取marker点的数据失败 ===>>>::", error);
          });
      })
    },
    init(map) {
      this.map = map;
      this.map.setZoom(5);
      this.getPointData().then((res) => {
        console.log("获取到的marker点的数据 ===>>>", res);
        this.pointData = res;
        // 根据获取到的marker点数据，向地图添加marker点
        this.pointData && this.drawMarker(this.pointData);
      });
    },
    drawMarker(data) {
      let self = this;
      this.defaultUserImg = require("@/assets/images/user_default.png");
      this.selectedUserImg = require("@/assets/images/user_selected.png");
      data.features.forEach((feature) => {
        let element = document.createElement("div");
        element.style.width = "33px";
        element.style.height = "45px";
        element.style.backgroundImage = `url(${this.defaultUserImg})`;
        element.style.backgroundRepeat = "no-repeat";
        element.style.backgroundSize = "cover";
        const marker = new mapboxgl.Marker({
          element,
          anchor: "bottom",
        })
          .setLngLat([feature.geometry.coordinates[0], feature.geometry.coordinates[1]])
          .addTo(this.map);
        marker.properties = feature.properties;
        marker.getElement().addEventListener("click", function(e) {
          e.stopPropagation(); // 阻止事件传播到地图下面的元素
          self.handleClickMarker(marker); // 在点击时执行的操作
        });
        this.markerList.push(marker);
      });
    },
    handleClickMarker(data) {
      console.log("当前点击marker数据 ===>>>", data);
      this.closeDetail(); // 关闭详情
      // 清除之前高亮，重新高亮当前点击marker
      EventBus.$emit("clearSelMarker");
      data._element.style.backgroundImage = `url(${this.selectedUserImg})`;
      this.setDeviceCard(data); // 弹出气泡框
    },
    clearSelMarker() {
      this.markerList.forEach((marker) => {
        marker._element.style.backgroundImage = `url(${this.defaultUserImg})`;
      });
    },
    setDeviceCard(data) {
      let self = this;
      this.removeDeviceCard(); // 清空设备卡片
      let element = document.createElement("div");
      const lngLat = [data._lngLat.lng, data._lngLat.lat];
      const comVue = Vue.extend(DeviceCard);
      const deviceCardComponent = new comVue({
        data() {
          return {
            value: data,
          }
        },
        methods: {
          closeDeviceCard() {
            self.removeDeviceCard();
            EventBus.$emit("clearSelMarker");
            self.detailVisible = false;
          },
          showDetail(name) {
            self.detailTitle = name;
            self.detailVisible = true;
          }
        }
      });
      deviceCardComponent.$mount(element);
      const marker = new mapboxgl.Marker({
          element: deviceCardComponent.$el,
          anchor: "bottom",
        })
      .setLngLat(lngLat)
      .setOffset([0, -60]) // 设置偏移，例如向上偏移30个像素
      .addTo(this.map);
      this.deviceCardMarkerList.push(marker);
      this.map.setCenter(lngLat);
    },
    removeDeviceCard() {
      if (this.deviceCardMarkerList.length > 0) {
        this.deviceCardMarkerList.forEach((item) => {
          item.remove();
        });
        this.deviceCardMarkerList = [];
      }
    },
    // 关闭详情
    closeDetail() {
      this.detailTitle = "";
      this.detailVisible = false;
    }
  }
}
</script>
<style lang="scss" scoped>
.marker-container {
  position: absolute;
  top: 50px;
  right: 10px;
  .detail-box {
    width: 400px;
    min-height: 300px;
    background-color: #fff;
    border-radius: 10px;
    padding: 3px 6px;
    display: flex;
    justify-content: space-between;
    .close {
      cursor: pointer;
    }
  }
}
</style>
